package com.gzpi.hwgggh.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gzpi.hwgggh.entity.*;
import com.gzpi.hwgggh.mapper.*;
import com.gzpi.hwgggh.service.GGPService;
import com.gzpi.hwgggh.sysenum.EnumErrorCode;
import com.gzpi.hwgggh.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * @date : 2020-12-18 15:01
 **/
@Service
@Transactional
public class GGPServiceImpl implements GGPService {

    @Autowired
    private GGPMapper ggpMapper;

    @Autowired
    private DWXMapper dwxMapper;

    @Autowired
    private DWCMapper dwcMapper;

    @Autowired
    private DWTPMapper dwtpMapper;

    @Autowired
    private DWFJMapper dwfjMapper;

    @Override
    public Boolean addGgp(GGP ggp) {
        try {
            if (ggpMapper.insertGgp(ggp) > 0) return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean updateGgp(GGP ggp) {
        try {
            if (ggpMapper.updateGgp(ggp) > 0) return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean selectGgpByIdisexist(String ID) {
        /*try {
            if(ggpMapper.selectGgpByIdisexist(ID) >0)return true;
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        return false;
    }

    @Override
    public Result editGgp(String xzJson, String ghJson, String ccJson, HttpServletRequest request) {
        boolean isedit = false; //是否编辑
        List<GGP> ggps = null;  //存放json转对象 （数据）

        List<String> deleteFiles = new ArrayList<>();//保存要删除广告牌证件文件名
        List<Map<String, String>> updateFiles = new ArrayList<>();//保存要修改广告牌证件文件名


        Map<String, Object> map = new HashMap<>();//条件
        if (StringUtils.isNotBlank(xzJson)) { //编辑现状广告牌
            ggps = mergeGgp(JSON.parseArray(xzJson, GGP.class)); //json转对象并合并信息

            if (ggps != null) {
                for (GGP ggp : ggps) { //遍历对象
                    ggp.setTableName("GGP_X"); //操作表
                    editGgp(ggp);//公共方法
                }
                isedit = true;
            }
        }
        if (StringUtils.isNotBlank(ghJson)) { //编辑规划广告牌
            ggps = mergeGgp(JSON.parseArray(ghJson, GGP.class));//json转对象并合并信息
            boolean isContainCC = false;
            boolean isAdd = true;
            String dwcid = CommonTools.getCurrentTimeMillis();
            if (ggps != null) {
                for (GGP ggp : ggps) {//遍历对象
                    if ("拆除".equals(ggp.getGHCS())) {
                        ggp.setTableName("GGP_C");//操作表
                        String dwxid = ggpMapper.selectDWXID(ggp.getFID(), "DW_G");
                        map.put("FID", dwxid);
                        if (!(dwcMapper.selectDWCcountByMap(map) > 0) && isAdd) { //判断拆除点位是否存在\
                            map.put("ID", dwxid);
                            DWX newdwx = dwxMapper.selectDWXByID(map);  //获取现状点位信息
                            DWC dwc = new DWC(newdwx); //将现状点位信息copy到拆除点位信息
                            dwc.setID(dwcid);
                            dwcMapper.insertDWC(dwc); //新建拆除点位信息
                            isAdd = false;
                        }
                        ggp.setDWTYPE("拆除点");
                        isContainCC = true;
                    } else {
                        ggp.setTableName("GGP_G");//操作表
                        ggp.setDWTYPE("规划点");
                    }
                    if (ggpMapper.selectGgpByIdisexist(ggp.getGGBH(), ggp.getFID(), ggp.getTableName()) > 0) {
                        ggpMapper.updateGgp(ggp);
                    } else {
                        String ghggbh = ggp.getGGBH();
                        String ghggfid = ggp.getFID();
                        if (isContainCC) {//判断是否要新增拆除广告牌
                            ggp = ggpMapper.selectGGPOneByGgbhAndFid(ggp.getGGBH(), ggp.getFID(), "GGP_G");//获取规划广告牌
                            ggp.setTableName("GGP_C");
                            ggp.setDWTYPE("拆除点");
                            ggp.setGHCS("拆除");
                            dwcid = ggpMapper.selectDWID(ggp.getFID(),"DW_C","DW_G");
//                            String dwcid = ggpMapper.selectDWID(ggp.getFID(), "DW_C", "DW_G");
                            String s = ggpMapper.selectGGPMaxID(dwcid, ggp.getTableName()); //获取拆除最大点位编号
                            if (StringUtils.isNotBlank(s)) {//判断
                                Integer id = Integer.valueOf(s.substring(s.indexOf("_") + 1));
                                id++; //最大id加1
                                if (id < 10) {
                                    ggp.setGGBH(dwcid + "_0" + id);
                                } else {
                                    ggp.setGGBH(dwcid + "_" + id);
                                }
                            } else {
                                ggp.setGGBH(ggp.getFID() + "_01");
                            }
                            ggp.setFID(dwcid);
                        }
                        ggp.setID(CommonTools.getCurrentTimeMillis());
                        if (ggpMapper.insertGgp(ggp) > 0) {
                            if (isContainCC) {
                                String ggpid = ggpMapper.selectGGPID(ghggbh, ghggfid, "GGP_G");//获取广告牌唯一id
                                ggpMapper.deleteGgp(ghggbh, ghggfid, "GGP_G");
                                map.put("GGFID", ggpid);
                                String ggpzj = dwfjMapper.selectSZRGGgpzj(map); //获取广告牌证件路径
                                String dwfjid = dwfjMapper.selectFJID(ggpMapper.selectDWXID(ggps.get(0).getFID(), "DW_G"));
                                map.put("FID",dwfjid);
                                map.remove("ID");
                                if (dwfjMapper.deleteSZRG(map) > 0) { //删除广告牌证件
                                    if (StringUtils.isNotBlank(ggpzj)) {
                                        String filename = ggpzj.substring(ggpzj.lastIndexOf("/") + 1); //截取文件名
                                        deleteFiles.add(filename); //保存文件名
                                    }
                                }
                            }
                        }
                    }
                }
                if (isContainCC) { //判断是否有新增拆除
                    String fid = ggps.get(0).getFID();//广告牌外键ID
                    map.put("FID", fid);
                    map.put("tableName", "GGP_G");
                    map.remove("GGBH");
                    List<GGP> ggpList = ggpMapper.selectGGPByMap(map); //获取所有规划广告牌

                    String dwxid = ggpMapper.selectDWXID(ggps.get(0).getFID(), "DW_G");
                    String xh = dwxMapper.selectDWXH(dwxid);
                    if (xh != null) {
                        xh = "-" + xh;
                    } else {
                        xh = "";
                    }
                    if (ggpList != null && ggpList.size() > 0) for (int i = 0; i < ggpList.size(); i++) { //遍历规划广告牌
                        GGP ggp = ggpList.get(i);
                        int id = (i + 1);
                        String originalId = ggp.getGGBH();// 原编号
                        String presentId;// 新编号
                        if (id < 10) { //重新编号
                            presentId = (ggp.getFID() + "_0" + id);
                        } else {
                            presentId = (ggp.getFID() + "_" + id);
                        }
                        ggpMapper.updateGGPID(originalId, presentId, "GGP_G", fid);
                    }

                    String dwfjid = dwfjMapper.selectFJID(dwxid);
                    if (StringUtils.isNotBlank(dwfjid)) {
                        map.put("FID", dwfjid);
                        List<SZRG> szrgs = dwfjMapper.selectSZRGList(map); //获取规划广告牌设置人信息
                        if (szrgs != null && szrgs.size() > 0) {
                            for (int i = 0; i < szrgs.size(); i++) { //遍历规划广告牌设置人
                                SZRG szrg = szrgs.get(i);
                                int id = (i + 1);//新序号
                                String orFileName = szrg.getGGPZJ().substring(szrg.getGGPZJ().lastIndexOf("/") + 1); //原文件名
                                String url = szrg.getGGPZJ().substring(0, szrg.getGGPZJ().lastIndexOf("/") + 1); //保存文件的路径
                                String originalId = szrg.getGGBH();// 原编号
                                String presentId;// 新编号
                                if (id < 10) { //重新编号
                                    presentId = (szrg.getGGFID() + "_0" + id);
                                } else {
                                    presentId = (szrg.getGGFID() + "_" + id);
                                }
                                String newFileName = "G("+szrg.getGGFID()+")" + orFileName.substring(orFileName.indexOf(")") + 1); //新文件名


                                map.put("originalId", originalId); //原广告牌编号
                                map.put("presentId", presentId); //新广告牌编号
                                map.put("GGPZJ", url + newFileName); //设置新文件名称
                                map.put("FID", dwfjid);//点位附件id
                                if (dwfjMapper.updateSZRGGGBH(map) > 0) {
                                    Map<String, String> fileMap = new HashMap<>();
                                    fileMap.put("orFileName", orFileName); //原文件名
                                    fileMap.put("newFileName", newFileName); //新文件名
                                    fileMap.put("savePath", HwggConstants.SAVE_PATH + dwxid + File.separator + "FJ"); //文件保存路径
                                    updateFiles.add(fileMap); //保存到集合
                                }
                            }
                            if (deleteFiles.size() > 0) {
                                for (String filename : deleteFiles) { //遍历要删除文件名的集合
                                    FileUtil.deleteFile(request, filename, HwggConstants.SAVE_PATH + dwxid + File.separator + "FJ");//删除文件
                                }
                            }
                            if (updateFiles.size() > 0) {
                                for (Map<String, String> updateFile : updateFiles) { //遍历要修改文件名的集合
                                    FileUtil.renameFile(updateFile.get("savePath"), updateFile.get("orFileName"), updateFile.get("newFileName"));//修改文件名
                                }
                            }
                        }
                    }
                }
                isedit = true;
            }
        }
        if (StringUtils.isNotBlank(ccJson)) { //编辑拆除广告牌
            ggps = mergeGgp(JSON.parseArray(ccJson, GGP.class));
            if (ggps != null) {
                for (GGP ggp : ggps) {
                    ggp.setTableName("GGP_C");
                    ggp.setDWTYPE("拆除点");
                    ggp.setGHCS("拆除");
                    editGgp(ggp);//公共方法
                }
                isedit = true;
            }
        }
        if (isedit) {
            Result<Object> result = Result.createSuccess(EnumErrorCode.SUCCESS_MESSAGE.toString("保存成功"));
            return result;
        } else {
            return Result.createError(EnumErrorCode.ERROR_MESSAGE.toString("保存失败"));
        }

    }

    //保存修改广告牌信息
    private void editGgp(GGP ggp){
        if (ggpMapper.selectGgpByIdisexist(ggp.getGGBH(), ggp.getFID(), ggp.getTableName()) > 0) {
            ggpMapper.updateGgp(ggp);//修改广告牌信息
        } else {
            ggp.setID(CommonTools.getCurrentTimeMillis());
            ggpMapper.insertGgp(ggp); //新增广告牌信息
        }
    }

    private Result CommontEditGGCC(String fid, String dataJson, String dwbh, String type, MultipartFile file, HttpServletRequest request) {
        String dwxid = ""; //点位id
        String ggptable = ""; //广告牌数据表
        String fileName = file != null ? file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) : ""; //图片名称
        String DWTYPE = ""; //广告牌点位类型
        String GHCS = "";  //规划措施
        Map<String, Object> map = new HashMap<>();

        if ("X".equals(type)) {
            dwxid = fid;
            ggptable = "GGP_X";
            fileName = "XZT_" + dwxid;
        } else if ("G".equals(type)) {
            dwxid = ggpMapper.selectDWXID(fid, "DW_G");
            ggptable = "GGP_G";
            fileName = "GHT_" + dwxid;
            DWTYPE = "规划点";
            GHCS = "保留";
        } else if ("C".equals(type)) {
            dwxid = ggpMapper.selectDWXID(fid, "DW_C");
            ggptable = "GGP_C";
            fileName = "CCT_" + dwxid;
            DWTYPE = "拆除点";
            GHCS = "拆除";
        }


        HashMap<String, String> map1 = JSON.parseObject(dataJson, new TypeReference<HashMap<String, String>>() {
        });

        Map<String, String> map2 = new HashMap<>();

        List<String> bcKey = null;

        if (map1 != null) {
            bcKey = new ArrayList<>(map1.keySet());
            for (String key : map1.keySet()) {
                map2.put("FID", fid);
                map2.put("DRAWID", key);
                map2.put("GGCC", map1.get(key));
                map2.put("tableName", ggptable);
                if (ggpMapper.selectCountByMap(map2) > 0) {
                    ggpMapper.updateGgpGGCC(map2);
                } else {
                    map2.put("ID", CommonTools.getCurrentTimeMillis());
                    map2.put("GHCS", GHCS);
                    map2.put("DWTYPE", DWTYPE);
                    Result newGGPID = getNewGGPID(type, dwbh, fid);
                    if (newGGPID.isSuccess()) {
                        Map<String, String> data = (Map<String, String>) newGGPID.getData();
                        map2.put("GGBH", data.get("ggpid"));
                        ggpMapper.insertGgpGGCC(map2);
                    }
                }
            }
        }

        if (ggpMapper.deleteGgpNotInKey(fid, bcKey, ggptable) > 0) {
            System.out.println("删除");
            List<Map<String, String>> list = ggpMapper.selectGGBHList(fid, ggptable);
            for (int i = 0; i < list.size(); i++) {
                int id = (i + 1);
                String originalId = list.get(i).get("GGBH");// 原编号
                String presentId;// 新编号
                if (id < 10) { //重新编号
                    presentId = (fid + "_0" + id);
                } else {
                    presentId = (fid + "_" + id);
                }
                ggpMapper.updateGGPID(originalId, presentId, ggptable, fid);
            }
        }

        Result result = saveImg(file, dwxid, dwbh, fileName, request);
        if (!result.isSuccess()) {
            return result;
        }

        //获取规格尺寸
        List<Map<String, String>> list = ggpMapper.selectGGCCList(fid, ggptable);


        Map<String, Object> ggccMap = new HashMap<>();

        if (list != null && list.size() > 0) {
            for (Map<String, String> data : list) {
                String id = data.get("GGBH").substring(data.get("GGBH").indexOf("_") + 1);
                CommonTools.getMapData(ggccMap, data.get("GGCC"), id);
            }
        }

        String ggccStr = CommonTools.mapSort(ggccMap);


        return Result.createSuccess("成功", new HashMap<String, String>() {{
            put("GGCC", ggccStr);
            put("URL", result.getData().toString());
        }});
    }

    private Result saveImg(MultipartFile file, String dwxid, String dwbh, String fileName, HttpServletRequest request) {
        FileResult fileResult = null;
        Map<String, Object> map = new HashMap<>();
        if (file != null) {

//            MultipartFile file = null;
           /* try {
                file=createNewFile(file1,file1.getOriginalFilename());
            } catch (IOException e) {
                e.printStackTrace();
            }*/

            map.put("FID", dwxid);
            DWTP dwtp = dwtpMapper.selectDWTPbyMap(map);//获取已有点位图片对象
            if (dwtp == null) dwtp = new DWTP();
            String start = fileName.substring(0, fileName.indexOf("_") + 1);
            switch (start) {
                case "GHT_":
                    if (StringUtils.isNotBlank(dwtp.getGHT()))
                        fileName = dwtp.getGHT().substring(dwtp.getGHT().lastIndexOf("/") + 1, dwtp.getGHT().lastIndexOf("."));
                    break;
                case "XZT_":
                    if (StringUtils.isNotBlank(dwtp.getXZT()))
                        fileName = dwtp.getXZT().substring(dwtp.getXZT().lastIndexOf("/") + 1, dwtp.getXZT().lastIndexOf("."));
                    break;
                case "CCT_":
                    if (StringUtils.isNotBlank(dwtp.getCCT()))
                        fileName = dwtp.getCCT().substring(dwtp.getCCT().lastIndexOf("/") + 1, dwtp.getCCT().lastIndexOf("."));
                    break;
            }

            //保存文件
            fileResult = FileUtil.saveFileToPath(request, file, HwggConstants.SAVE_PATH + dwxid, HwggConstants.MAPPING_PATH + dwxid, fileName);
            if (!fileResult.isFlag()) {
                return Result.createError(EnumErrorCode.ERROR_MESSAGE.toString("上传图片失败"));
            }
            //根据文件名前缀保存到对应字段
            switch (fileResult.getFileName().substring(0, fileResult.getFileName().indexOf("_") + 1)) {
                case "GHT_":
                    dwtp.setGHT(fileResult.getHttpUrl());
                    break;
                case "XZT_":
                    dwtp.setXZT(fileResult.getHttpUrl());
                    break;
                case "CCT_":
                    dwtp.setCCT(fileResult.getHttpUrl());
                    break;
            }

            if (dwtpMapper.selectDWTPCountbyMap(map) > 0) {
                dwtpMapper.updateDWTP(dwtp);
            } else {
                dwtp.setID(CommonTools.getCurrentTimeMillis());
                dwtpMapper.insertDWTP(dwtp);
            }

        }
        return Result.createSuccess(EnumErrorCode.ERROR_MESSAGE.toString("上传图片成功"), fileResult != null ? fileResult.getHttpUrl() : "");
    }

    /*public MultipartFile createNewFile(MultipartFile file,String fileName) throws IOException {
        InputStream is = file.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > -1) {
            baos.write(buffer, 0, length);
        }
        baos.flush();

        return new MockMultipartFile(fileName, fileName, file.getContentType(), buffer);
    }
*/
    @Override
    public Result editGGCC(String json, String dataJson, MultipartFile xzfile, MultipartFile ghfile, HttpServletRequest request) {

        Map<String, String> map = JSON.parseObject(json, new TypeReference<HashMap<String, String>>() {
        });
        boolean isSuccess = false;
        Map<String, String> map1 = new HashMap<>();
        String DWBH = "";
        if (map.containsKey("DWBH")) DWBH = map.get("DWBH");
        if (map.containsKey("XZID")) {
            Result result = CommontEditGGCC(map.get("XZID"), dataJson, DWBH, "X", xzfile, request);
            isSuccess = result.isSuccess();
            map1.put("xzggcc", getMapData((Map<String, String>) result.getData(), "GGCC"));
            map1.put("xzUrl", getMapData((Map<String, String>) result.getData(), "URL"));
        }
        if (map.containsKey("GHID")) {
            Result result = CommontEditGGCC(map.get("GHID"), dataJson, DWBH, "G", ghfile, request);
            isSuccess = result.isSuccess();
            map1.put("ghggcc", getMapData((Map<String, String>) result.getData(), "GGCC"));
            map1.put("ghUrl", getMapData((Map<String, String>) result.getData(), "URL"));
        }
        if (map.containsKey("CCID")) {
            Result result = CommontEditGGCC(map.get("CCID"), dataJson, DWBH, "C", ghfile, request);
            isSuccess = result.isSuccess();
            map1.put("ccggcc", getMapData((Map<String, String>) result.getData(), "GGCC"));
            map1.put("ccUrl", getMapData((Map<String, String>) result.getData(), "URL"));
        }
        if (isSuccess) {
            return Result.createSuccess("编辑成功", map1);
        } else {
            return Result.createError("编辑失败");
        }

    }

    private String getMapData(Map<String, String> map, String key) {
        return map.get(key);
    }

    private List<GGP> mergeGgp(List<GGP> ggps) {
        Map<String, GGP> map = new HashMap<>();
        for (GGP ggp : ggps) {
            String id = ggp.getGGBH();
            if (map.containsKey(id)) {
                GGP g = map.get(id);
                if (StringUtils.isNotBlank(ggp.getGHCS())) {
                    g.setGHCS(ggp.getGHCS());
                }
                if (StringUtils.isNotBlank(ggp.getSZWZ())) {
                    g.setSZWZ(ggp.getSZWZ());
                    g.setQTWZ(ggp.getQTWZ());
                }
                if (StringUtils.isNotBlank(ggp.getNRLX())) {
                    g.setNRLX(ggp.getNRLX());
                }
                if (StringUtils.isNotBlank(ggp.getGYXS())) {
                    g.setGYXS(ggp.getGYXS());
                    g.setQTGY(ggp.getQTGY());
                }
                if (StringUtils.isNotBlank(ggp.getCLYD())) {
                    g.setCLYD(ggp.getCLYD());
                    g.setQTCL(ggp.getQTCL());
                }
                if (StringUtils.isNotBlank(ggp.getGGCC())) {
                    g.setGGCC(ggp.getGGCC());
                }
                if (StringUtils.isNotBlank(ggp.getZM())) {
                    g.setZM(ggp.getZM());
                }
                if (StringUtils.isNotBlank(ggp.getZYWT())) {
                    g.setZYWT(ggp.getZYWT());
                }
            } else {
                map.put(id, ggp);
            }
        }
        List<GGP> newGpps = new ArrayList<>();
        for (String s : map.keySet()) {
            newGpps.add(map.get(s));
        }
        return newGpps;
    }


    @Override
    public Result getNewGGPID(String dwtype, String dwbh, String fid) {
        if (StringUtils.isNotBlank(dwtype) && StringUtils.isNotBlank(dwbh) && StringUtils.isNotBlank(fid)) {
            Map<String, Object> map = new HashMap<>(); //条件
            String id = "";
            if ("X".equals(dwtype)) {
                id = ggpMapper.selectGGPMaxID(fid, "GGP_X"); //现状广告牌最大编号
            } else if ("G".equals(dwtype)) {
                id = ggpMapper.selectGGPMaxID(fid, "GGP_G"); //规划广告牌最大编号
            } else if ("C".equals(dwtype)) {
                id = ggpMapper.selectGGPMaxID(fid, "GGP_C"); //拆除广告牌最大编号
            }
            if (StringUtils.isNotBlank(id)) {
                id = id.substring(id.indexOf("_") + 1);  //截取编号
                Integer i = Integer.valueOf(id);
                i++;
                if (i < 10) {
                    map.put("ggpid", fid + "_0" + i);
                    map.put("bh", "0" + i);
                } else {
                    map.put("ggpid", fid + "_" + i);
                    map.put("bh", i.toString());
                }
            } else {
                map.put("ggpid", fid + "_01");
                map.put("bh", "01");
            }
            return Result.createSuccess("获取新编号成功", map);
        }
        return Result.createError("参数不能为空");
    }


}
